package com.iot.core.utils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;

public class EntityValidator {

    private static ValidatorFactory factory;

    private static Validator validator;

    static {
        factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 根据实体Excel导入实体验证数据有效性
     * @param list
     * @param index
     * @param <E>
     * @return
     */
    public static <E> String validate(List<E> list, int index) {
        //根据实体验证规则验证
        StringBuilder exceptionSb = new StringBuilder();
        for(E e:list){
            Set<ConstraintViolation<E>> set = validator.validate(e);
            for (ConstraintViolation<E> c : set) {
                exceptionSb.append("第"+index+"行数据"+c.getMessage()+"；");
            }
            index++;
        }
        return exceptionSb.toString();
    }

    /**
     * 验证实体有效性
     * @param e
     * @param <E>
     * @return
     */
    public static <E> String validateDO(E e) {
        //根据实体验证规则验证
        StringBuilder exceptionSb = new StringBuilder();
        Set<ConstraintViolation<E>> set = validator.validate(e);
        for (ConstraintViolation<E> c : set) {
            exceptionSb.append(c.getMessage()+"；");
        }
        return exceptionSb.toString();
    }

}
